﻿using System;
using System.Text;
using ERP.Web.Core.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace ERP.Web.Core.Configuration
{
    public static class AuthConfigurator
    {
        public static IServiceCollection Configure(IServiceCollection services, IConfiguration configuration)
        {
            var authConfig = configuration.GetSection("Authentication").GetSection("JwtBearer");
            var symmetricKeyAsBase64 = authConfig["Secret"];
            var keyByteArray = Encoding.UTF8.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,//是否验证SecurityKey
                IssuerSigningKey = signingKey,//拿到SecurityKey

                ValidateIssuer = true,//是否验证Issuer
                ValidIssuer = authConfig["Issuer"],//Issuer，这两项和前面签发jwt的设置一致

                ValidateAudience = true,////是否验证Audience
                ValidAudience = authConfig["Audience"],//Audience

                ValidateLifetime = true,//是否验证失效时间

                ClockSkew = TimeSpan.Zero
            };

            var tokenOptions = new TokenProviderOptions(
                    authConfig["Issuer"],
                    authConfig["Audience"],
                    signingCredentials);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                //不使用https
                o.RequireHttpsMetadata = false;
                o.TokenValidationParameters = tokenValidationParameters;
            });
            services.AddSingleton(tokenOptions);
            return services;
        }
    }
}
